//==================================================
//
//	Ctimer use high-resolution time for morden comp
//  due to coop between MS & Intel
//	Support: Windows 2000 and above
//
//==================================================

#ifndef CTIMER_H
#define CTIMER_H

#include <windows.h>

/// Create a Timer, which will immediately begin counting
/// up from 0.0 seconds.
/// You can call reset() to make it start over.
class CTimer {
  public:
    CTimer() {
      reset();
    }
    /// reset() makes the timer start over counting from 0.0 seconds.
    void reset() {
      unsigned __int64 pf;
      QueryPerformanceFrequency( (LARGE_INTEGER *)&pf );
      freq = 1.0 / (double)pf;
      QueryPerformanceCounter( (LARGE_INTEGER *)&baseTime );
	  totalTime = 0;
	  timeElapsed = 0;
	  lastTime = 0;
	  Paused = false;
    }
    /// seconds() returns the number of seconds (to very high resolution)
    /// elapsed since the timer was last created or reset().
    double seconds() {
      unsigned __int64 val;
      QueryPerformanceCounter( (LARGE_INTEGER *)&val );
      return (val - baseTime) * freq;
    }
	/// get time elapsed from last time called in second
	double TimeElapsed()
	{
		double t = seconds();
		totalTime += timeElapsed = t - lastTime;
		lastTime = t;
		return timeElapsed;
	}
	/// get the total time the clock has passed in second
	double TotalTime() const
	{
		return totalTime;
	}
	/// pause the clock
	/// store the current time in  lastTime
	/// sotre the tempo time passed in time Elapsed
	/// wait for call Resume()
	void Pause()
	{
		if(Paused == false){
			double t = seconds();
			timeElapsed = t - lastTime;
			lastTime = t;
			Paused = true;
		}		
	}
	/// resume the clock to the prePause state
	/// offset the clock pausedTime
	void Resume()
	{
		if(Paused)
		{
			double t = seconds();
			lastTime = t - timeElapsed;
			Paused = false;
		}
	}
  private:
    double freq;				/// high-resolution frequency
    unsigned __int64 baseTime;	/// the basetime when clock was reset() 
	double totalTime;
	double timeElapsed;
	double lastTime;
	bool Paused;
};

#endif